import './style.less';
import dayjs from 'dayjs';
import _, { set } from 'lodash';
import BanImg from '@/assets/ban.png';
import { paiBan } from '@/utils/helper';
import { useEffect, useState } from 'react';
import { banService } from '@/utils/leancloud-helper';
import { Button, Space, DatePicker } from 'antd-mobile';
import {useNavigate} from 'react-router-dom'

const getMonday = (d) => {
  d = new Date(d);
  const day = d.getDay();
  const diff = d.getDate() - day + (day == 0 ? -6 : 1); // adjust when day is sunday
  return new Date(d.setDate(diff));
};

const Ban = () => {
  useEffect(() => {
    syncPage();
  }, []);
  const [showSubBtn, setShowSubBtn] = useState(false);
  const [visible, setVisible] = useState(false);
  const [time, setTime] = useState(new Date());
  const [leftTimer, setLeftTimer] = useState([]);
  const [tempBan, setTempBan] = useState([]);

  // 生成页面所需的数据
  const computeShowTime = (selectTime, bans) => {
    if (selectTime) {
      setTime(selectTime);
    }

    // 获取指定日期所在周的周一日期
    const monday = getMonday(selectTime ? selectTime : time);
    console.log(dayjs(selectTime ? selectTime : time).format('MM-DD'));

    // 将每周定位7天
    let cloneBan = tempBan;
    if (bans) {
      cloneBan = _.cloneDeep(bans);
      cloneBan.forEach((element) => {
        element.unshift([null, null, null]);
      });
    }

    // 给所有的元素追加日期
    const timer = [monday];
    for (let index = 0; index < cloneBan.length - 1; index++) {
      const lastTimer = timer[timer.length - 1];
      timer.push(dayjs(lastTimer).add(7, 'day'));
    }
    setTempBan(cloneBan);
    setLeftTimer(timer);
  };

  const syncPage = async () => {
    const {
      attributes: { time, ban }
    } = await banService.query();
    computeShowTime(time, JSON.parse(ban));
  };

  // 创建生成排班(时间不变 顺序变)
  const onGenBan = async () => {
    setShowSubBtn(true);
    const res = await paiBan();
    computeShowTime(null, res);
  };

  // 创建生成时间（顺序不变 时间变）
  const onGenTime = (val) => {
    setShowSubBtn(true);
    setVisible(false);
    computeShowTime(val);
  };

  // 保存
  const save = () => {
    const cloneBan = _.cloneDeep(tempBan);
    cloneBan.forEach((element) => {
      element.shift();
    });

    banService.update({
      time,
      ban: JSON.stringify(cloneBan)
    });
  };

  // 重置
  const onResetForm = () => {
    syncPage();
    setShowSubBtn(false);
  };

  const navigate =  useNavigate();
  const clickLogo = ()=>{
    navigate('admin')
  }

  return (
    <>
      <DatePicker
        title="时间选择"
        value={time}
        visible={visible}
        onClose={() => {
          setVisible(false);
        }}
        onConfirm={onGenTime}
      />

      <div className="ban">
        <div className='logo' onDoubleClick={clickLogo}>
          <img src={BanImg} />
          <div>排班表</div>
        </div>
        <div className="btns">
          <Button
            size="small"
            color="primary"
            onClick={() => {
              print();
            }}>
            打印
          </Button>
        </div>
        {/* <div className="btns">
          <Space>
            <Button
              size="small"
              color="primary"
              onClick={() => {
                setVisible(true);
              }}>
              重置执行时间
            </Button>

            <Button
              size="small"
              color="primary"
              onClick={() => {
                onGenBan();
              }}>
              重置排班
            </Button>
            {showSubBtn && (
              <Space>
                <Button size="small" color="danger" onClick={save}>
                  保存
                </Button>
                <Button size="small" onClick={onResetForm}>
                  取消
                </Button>
              </Space>
            )}
          </Space>
        </div> */}

        {/* 遍历周 */}
        {tempBan.map((item, index) => (
          <div className='week-group' key={index}>
            <div className='day-group'>{dayjs(leftTimer[index]).format('YYYY-MM-DD')}</div>

            <div className="week">
              {/* 顶部标题 */}
              <div className="day head">
                <span className="porn">值班日期</span>
                <span className="porn">{item[1][0].role.name}</span>
                <span className="porn">{item[1][1].role.name}</span>
                <span className="porn">{item[1][2].role.name}</span>
              </div>

              {/* 遍历天 */}
              {item.map((it, idx) => (
                <div className="day" key={index + '-' + idx}>
                  <span className="porn">
                    {dayjs(leftTimer[index]).add(idx, 'day').format('MM-DD')} / 周{idx + 1}
                  </span>
                  {/* 遍历角色 */}
                  {it.map((i, x) => (
                    <span className="porn" key={index + '-' + idx + '-' + x}>
                      {i?.name ? i.name : '-'}
                    </span>
                  ))}
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </>
  );
};

export default Ban;
